package cn.yunyichina.provider.clinic.listener;

import cn.yunyichina.provider.clinic.dao.FuyinApplyDao;
import cn.yunyichina.provider.clinic.service.impl.PayServiceImpl;
import cn.yunyichina.provider.clinic.utils.DateUtils;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.dubbo.service.MessageService;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.XmlUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.listener.MessageListener;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class AppletWechatPayMessageListener implements MessageListener<Integer, String> {

    private Logger logger = LoggerFactory.getLogger(AppletWechatPayMessageListener.class);

    @Autowired
    private PayServiceImpl payService;

    public void onMessage(ConsumerRecord<Integer, String> integerStringConsumerRecord) {
//        String xmlString = "<xml><appid>wx2421b1c4370ec43b</appid><attach>支付测试</attach><bank_type>CFT</bank_type><fee_type>CNY</fee_type><is_subscribe>Y</is_subscribe><mch_id>10000100</mch_id><nonce_str>5d2b6c2a8db53831f7eda20af46e531c</nonce_str><openid>oUpF8uMEb4qRXf22hE3X68TekukE</openid><out_trade_no>1409811653</out_trade_no><result_code>SUCCESS</result_code><return_code>SUCCESS</return_code><sign>B552ED6B279343CB493C5DD0D78AB241</sign><sub_mch_id>10000100</sub_mch_id><time_end>20140903131540</time_end><total_fee>1</total_fee><trade_type>JSAPI</trade_type><transaction_id>1004400740201409030005092168</transaction_id></xml>";
        String xmlString = integerStringConsumerRecord.value();
        logger.info("AppletWechatPayMessageListener.onMessage.xmlString -> {}", xmlString);

        try {
            Map<String, String> doc = XmlUtils.xmlToMap(xmlString);
            String orderNo = doc.get("out_trade_no");
            String openId = doc.get("openid");
            String appId = doc.get("appid");
            String pay_mode = doc.get("pay_mode");
//            Float payAmount = Float.parseFloat(doc.get("total_fee"));
            BigDecimal payAmount = new BigDecimal( doc.get("total_fee"));

            Map<String, Object> dataMap = new HashMap<String, Object>();

            dataMap.put("yyt_order_no", orderNo);
            dataMap.put("pay_time", DateUtils.dateToString(new Date()));
            dataMap.put("user_id", openId);
            dataMap.put("payee_app_id", appId);
            dataMap.put("pay_mode", pay_mode);
            dataMap.put("pay_amount", payAmount.intValue());

            if (payService == null) {
                payService = SpringContextHandler.getBean(PayServiceImpl.class);
            }
            Response response = payService.ackPayOrderByOrderNoOut(JsonUtils.toJsonString(dataMap), "");
            logger.info("onMessage 门诊写单 response:{}", JSON.toJSONString(response));
            if(response.getResultCode().equals("0")){
                //写单成功发送消息
                Response cacheResponse = CacheService.callUnderlineFromInternal("", "yyt.cache.wechat.applet.prepay.id.get",
                        "{\"order_no\":\"" + orderNo +" \"}");
                logger.info("获取缓存中的prepayid response:{}", JSON.toJSONString(cacheResponse));
                if ("0".equals(cacheResponse.getResultCode())) {
                    //查询订单
                    Response ordResponse = BaseService.callUnderlineFromInternal("", "yyt.base.order.by.order.no.out.get",
                            "{\"order_no\":\"" + orderNo +" \"}");
                    if (!"0".equals(ordResponse.getResultCode())) {
                        return ;
                    }
                    OrderExtVo orderExtVo = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);

                    JSONObject jsonObject = JSON.parseObject(cacheResponse.getResult());
                    String prepay_id = jsonObject.getString("prepay_id");
                    if(StringUtils.isNotBlank(prepay_id)){
                        Map<String,Object> msgMap = new HashedMap();
                        msgMap.put("to_user",openId);
                        msgMap.put("user_type","2");
                        msgMap.put("template_id","");
                        msgMap.put("form_id",prepay_id);
                        msgMap.put("org_app_code",orderExtVo.getOrgCode());

                        JSONObject data = new JSONObject();
                        JSONObject k1 = new JSONObject();
                        k1.put("value",orderExtVo.getUserName());
                        k1.put("color","#173177");
                        data.put("keyword1",k1);

                        JSONObject k2 = new JSONObject();
                        k2.put("value",orderNo);//订单号
                        k2.put("color","#173177");
                        data.put("keyword2",k2);

                        JSONObject k3 = new JSONObject();
                        k3.put("value",payAmount.divide(new BigDecimal(100)));
                        k3.put("color","#173177");
                        data.put("keyword3",k3);

                        JSONObject k4= new JSONObject();
                        k4.put("value",orderExtVo.getDeptName());
                        k4.put("color","#173177");
                        data.put("keyword4",k4);

                        JSONObject k5= new JSONObject();
                        k5.put("value", DateUtils.dateToString(new Date()));
                        k5.put("color","#173177");
                        data.put("keyword5",k5);

                        msgMap.put("data",data);
                        String json = JsonUtils.toJsonString(msgMap);
                        Response msgRsp = MessageService.callUnderlineFromInternal("yyt.message.msg.small.template.message.send", json);
                        logger.info("发送模板消息，返回" + JsonUtils.toJsonString(msgRsp));
                    }
                }
            }

        } catch (Exception e) {
            logger.error("onMessage error.", e);
        }
        logger.info("onMessage end.");
    }

    public static void main(String a[]){
        Map<String,Object> msgMap = new HashedMap();
        msgMap.put("to_user","opendididd");
        msgMap.put("user_type","2");
        msgMap.put("template_id","");
        msgMap.put("form_id","888888888");
        JSONObject data = new JSONObject();
        JSONObject k1 = new JSONObject();
        k1.put("value","wwb");
        k1.put("color","#173177");
        data.put("keyword1",k1);
        JSONObject k2 = new JSONObject();
        k2.put("value","YC201612125895959");
        k2.put("color","#173177");
        data.put("keyword2",k2);
        msgMap.put("data",data);
        String json = JsonUtils.toJsonString(msgMap);
        System.out.println(json);
    }

}
